package br.puc.casas.gui;

import java.awt.event.WindowEvent;

import javax.swing.JFrame;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

import br.puc.casas.dao.CasaDao;
import br.puc.casas.gui.processing.CasaAmarela;
import br.puc.casas.model.Ambiente;
import br.puc.casas.model.Casa;
import br.puc.casas.model.Telha;

public class ApplicationFrame extends JFrame implements InitializingBean,
		ApplicationContextAware {
	private static final long serialVersionUID = -2969353178252310240L;

	private CasaDao casaDao;

	private CasaAmarela casaAmarela;

	private Thread refresherThread;

	private ConfigurableApplicationContext applicationContext;

	public ApplicationFrame() {
		super("Casas");
	}

	public void afterPropertiesSet() throws Exception {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(500, 500);
		setVisible(true);

		Casa casa = casaDao.procurar(1L);
		if (casa == null) {
			casa = new Casa();
			casa.setComprimento(6);
			casa.setLargura(2);
			casa.setNumeroComodos(0);
			casa.setAmbiente(new Ambiente().setTemperatura(27));
			casa.setTelha(new Telha().setPeso(3.2f));
			casaDao.inserir(casa);
		}

		casaAmarela = new CasaAmarela(casa);
		add(casaAmarela);
		casaAmarela.init();
		casaAmarela.start();

		refresherThread = new Thread(new Refresher());
		refresherThread.setDaemon(true);
		refresherThread.start();
	}

	public void setCasaDao(CasaDao casaDao) {
		this.casaDao = casaDao;
	}

	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext =
				(ConfigurableApplicationContext) applicationContext;
	}

	@Override
	protected void processWindowEvent(WindowEvent windowEvent) {
		if (windowEvent.getNewState() == WindowEvent.WINDOW_CLOSED) {
			refresherThread.interrupt();
			applicationContext.close();
		}

		super.processWindowEvent(windowEvent);
	}

	private class Refresher implements Runnable {
		public void run() {
			while (true) {
				try {
					Thread.sleep(1000);
					casaDao.renovar(casaAmarela.getCasa());
				} catch (InterruptedException e) {
					break;
				}
			}
		}
	}
}
